package com.aims.server.controller;

import com.aims.server.common.ApiResponse;
import com.aims.server.common.ErrorCode;
import com.aims.server.dto.ExtAccountFormDTO;
import com.aims.server.entity.ExtAccountForm;
import com.aims.server.entity.ExtAccountItem;
import com.aims.server.service.ExtAccountFormService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 企业或集团外常用账户信息表Controller
 */
@RestController
@RequestMapping("/api/ext-accounts/forms")
public class ExtAccountFormController {
    @Resource
    private ExtAccountFormService extAccountFormService;

    /**
     * 新建整张表(抬头+多条明细一次提交)
     * POST /api/ext-accounts/forms
     * @param dto 表单DTO
     * @param bindingResult 校验结果
     * @return 表单ID
     */
    @PostMapping
    public ApiResponse<String> createForm(@Valid @RequestBody ExtAccountFormDTO dto,
                                          BindingResult bindingResult) {
        // 参数校验
        if (bindingResult.hasErrors()) {
            StringBuilder errorMsg = new StringBuilder();
            for (FieldError error : bindingResult.getFieldErrors()) {
                errorMsg.append(error.getField()).append(":").append(error.getDefaultMessage()).append(";");
            }
            return ApiResponse.error(ErrorCode.PARAM_INVALID, errorMsg.toString());
        }

        try {
            String formId = extAccountFormService.createForm(dto);
            return ApiResponse.success(formId);
        } catch (IllegalArgumentException e) {
            // operationType非法
            return ApiResponse.error(ErrorCode.OPERATION_TYPE_INVALID, e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error(50000, "创建失败:" + e.getMessage());
        }
    }

    /**
     * 按formId查询抬头与全量明细
     * GET /api/ext-accounts/forms/{formId}
     * @param formId 表单ID
     * @return 表单对象(含明细)
     */
    @GetMapping("/{formId}")
    public ApiResponse<ExtAccountForm> getFormById(@PathVariable String formId) {
        try {
            ExtAccountForm form = extAccountFormService.getFormById(formId);
            return ApiResponse.success(form);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("不存在")) {
                return ApiResponse.error(ErrorCode.FORM_NOT_FOUND);
            }
            return ApiResponse.error(50000, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 整体更新(允许增删改明细)
     * PUT /api/ext-accounts/forms/{formId}
     * @param formId 表单ID
     * @param dto 表单DTO
     * @param bindingResult 校验结果
     * @return 更新结果
     */
    @PutMapping("/{formId}")
    public ApiResponse<Void> updateForm(@PathVariable String formId,
                                        @Valid @RequestBody ExtAccountFormDTO dto,
                                        BindingResult bindingResult) {
        // 参数校验
        if (bindingResult.hasErrors()) {
            StringBuilder errorMsg = new StringBuilder();
            for (FieldError error : bindingResult.getFieldErrors()) {
                errorMsg.append(error.getField()).append(":").append(error.getDefaultMessage()).append(";");
            }
            return ApiResponse.error(ErrorCode.PARAM_INVALID, errorMsg.toString());
        }

        try {
            extAccountFormService.updateForm(formId, dto);
            return ApiResponse.success();
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(ErrorCode.OPERATION_TYPE_INVALID, e.getMessage());
        } catch (RuntimeException e) {
            if (e.getMessage().contains("不存在")) {
                return ApiResponse.error(ErrorCode.FORM_NOT_FOUND);
            }
            return ApiResponse.error(50000, "更新失败:" + e.getMessage());
        }
    }

    /**
     * 删除整张表
     * DELETE /api/ext-accounts/forms/{formId}
     * @param formId 表单ID
     * @return 删除结果
     */
    @DeleteMapping("/{formId}")
    public ApiResponse<Void> deleteForm(@PathVariable String formId) {
        try {
            extAccountFormService.deleteForm(formId);
            return ApiResponse.success();
        } catch (RuntimeException e) {
            if (e.getMessage().contains("不存在")) {
                return ApiResponse.error(ErrorCode.FORM_NOT_FOUND);
            }
            return ApiResponse.error(50000, "删除失败:" + e.getMessage());
        }
    }

    /**
     * 分页查询
     * GET /api/ext-accounts/forms
     * @param companyName 企业名称(模糊查询,可选)
     * @param mainApplyingAccount 主申请账号(模糊查询,可选)
     * @param contactPhone 联系电话(模糊查询,可选)
     * @param page 页码(从1开始,默认1)
     * @param size 每页数量(默认10)
     * @return 分页结果
     */
    @GetMapping
    public ApiResponse<Map<String, Object>> getFormList(
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false) String mainApplyingAccount,
            @RequestParam(required = false) String contactPhone,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Map<String, Object> result = extAccountFormService.getFormList(
                    companyName, mainApplyingAccount, contactPhone, page, size);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(50000, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 仅查询某表单的明细列表
     * GET /api/ext-accounts/forms/{formId}/items
     * @param formId 表单ID
     * @return 明细列表
     */
    @GetMapping("/{formId}/items")
    public ApiResponse<List<ExtAccountItem>> getItemsByFormId(@PathVariable String formId) {
        try {
            List<ExtAccountItem> items = extAccountFormService.getItemsByFormId(formId);
            return ApiResponse.success(items);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("不存在")) {
                return ApiResponse.error(ErrorCode.FORM_NOT_FOUND);
            }
            return ApiResponse.error(50000, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 导出表单为Word文档
     * GET /api/ext-accounts/forms/{formId}/export
     * @param formId 表单ID
     * @return Word文档文件流
     */
    @GetMapping("/{formId}/export")
    public ResponseEntity<byte[]> exportFormToWord(@PathVariable String formId) {
        try {
            // 调用服务导出Word文档
            byte[] wordBytes = extAccountFormService.exportFormToWord(formId);

            // 设置文件名(编码处理中文)
            String fileName = "企业或集团外币常用账户信息表_" + formId.substring(0, 8) + ".docx";
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                    .replaceAll("\\+", "%20");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentLength(wordBytes.length);

            return new ResponseEntity<>(wordBytes, headers, HttpStatus.OK);

        } catch (RuntimeException e) {
            if (e.getMessage().contains("不存在")) {
                // 表单不存在
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(("表单不存在: " + formId).getBytes(StandardCharsets.UTF_8));
            }
            // 导出失败
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("导出失败: " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("文件名编码失败: " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        }
    }

    /**
     * 导出表单为Word文档（V2新格式）
     * GET /api/ext-accounts/forms/{formId}/export-v2
     * @param formId 表单ID
     * @return Word文档文件流
     */
    @GetMapping("/{formId}/export-v2")
    public ResponseEntity<byte[]> exportFormToWordV2(@PathVariable String formId) {
        try {
            // 调用服务导出Word文档（V2格式）
            byte[] wordBytes = extAccountFormService.exportFormToWordV2(formId);

            // 设置文件名(编码处理中文)
            String fileName = "企业或集团外币常用账户信息表_V2_" + formId.substring(0, 8) + ".docx";
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                    .replaceAll("\\+", "%20");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentLength(wordBytes.length);

            return new ResponseEntity<>(wordBytes, headers, HttpStatus.OK);

        } catch (RuntimeException e) {
            if (e.getMessage().contains("不存在")) {
                // 表单不存在
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(("表单不存在: " + formId).getBytes(StandardCharsets.UTF_8));
            }
            // 导出失败
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("导出失败(V2): " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("文件名编码失败: " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        }
    }
}